package com.liu.mybatisplus.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author xianhuiyi
 */
public class StringUtil {
    public static <T> String toSql(QueryWrapper<T> queryWrapper) {
        String customSqlSegment = queryWrapper.getCustomSqlSegment();
        for (Map.Entry<String, Object> entry : queryWrapper.getParamNameValuePairs().entrySet()) {
            customSqlSegment = customSqlSegment.replace("#{ew.paramNameValuePairs." + entry.getKey() + "}", StringUtil.formatParamValue(entry.getValue()));
        }
        return customSqlSegment;
    }


    public static String formatParamValue(Object arg) {
        String paramValue;
        if (arg instanceof String) {
            paramValue = "'" + arg.toString().replace("'", "\\'") + "'";
        } else if (arg instanceof Date) {
            paramValue = "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) arg) + "'" ;
        } else if (arg != null) {
            paramValue = arg.toString();
        } else {
            paramValue = null;
        }
        return paramValue;
    }
}
